package group.rober.search.autoconfigure;

import group.rober.search.exception.SearchException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;

import java.io.File;
import java.io.IOException;

@EnableConfigurationProperties(SearchProperties.class)
@ComponentScan(basePackages = "group.rober.search")
public class SearchAutoConfiguration {
    private SearchProperties properties;

    public SearchAutoConfiguration(SearchProperties properties) {
        this.properties = properties;
    }

    @Bean
    public Analyzer getStandardAnalyzer(){
        return new StandardAnalyzer();
    }

    @Bean
    @Scope("prototype")
    public IndexWriterConfig getIndexWriterConfig(Analyzer analyzer){
        return new IndexWriterConfig(analyzer);
    }

    @Bean
    public Directory getDirectory(){
        Directory directory = null;
        if(properties.getDirectoryMode() == SearchProperties.DirectoryMode.Disk){
            try {
                File file = new File(properties.getDirectory());
                if(!file.exists())file.mkdirs();
                directory = FSDirectory.open(file.toPath());
            } catch (IOException e) {
                throw new SearchException("",e);
            }
        }else if(properties.getDirectoryMode() == SearchProperties.DirectoryMode.Memory){
            directory = new RAMDirectory();
        }
        return directory;
    }

    @Bean
    @Scope("prototype")
    public IndexWriter getIndexWriter(Directory directory, IndexWriterConfig indexWriterConfig) throws IOException {
        return new IndexWriter(directory, indexWriterConfig);
    }

}
